package com.nj.liandi.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.nj.liandi.common.exception.NoStockException;
import com.nj.liandi.common.to.mq.OrderTo;
import com.nj.liandi.common.to.mq.StockDetailTo;
import com.nj.liandi.common.to.mq.StockLockedTo;
import com.nj.liandi.common.utils.R;
import com.nj.liandi.gulimall.ware.bo.SkuWareHasStock;
import com.nj.liandi.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.nj.liandi.gulimall.ware.entity.WareOrderTaskEntity;
import com.nj.liandi.gulimall.ware.feign.OrderFeignService;
import com.nj.liandi.gulimall.ware.feign.ProductFeignServcie;
import com.nj.liandi.gulimall.ware.service.WareOrderTaskDetailService;
import com.nj.liandi.gulimall.ware.service.WareOrderTaskService;
import com.nj.liandi.gulimall.ware.vo.OrderItemVo;
import com.nj.liandi.gulimall.ware.vo.OrderVo;
import com.nj.liandi.gulimall.ware.vo.SkuHasStockVo;
import com.nj.liandi.gulimall.ware.vo.WareSkuLockVo;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nj.liandi.common.utils.PageUtils;
import com.nj.liandi.common.utils.Query;

import com.nj.liandi.gulimall.ware.dao.WareSkuDao;
import com.nj.liandi.gulimall.ware.entity.WareSkuEntity;
import com.nj.liandi.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    WareSkuDao wareSkuDao;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    WareOrderTaskService wareOrderTaskService;

    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;
    
    @Autowired
    ProductFeignServcie productFeignServcie;

    @Autowired
    OrderFeignService orderFeignService;
    

    /** description: 库存解锁
     * version: 1.0
     * date: 2021/11/4 10:54
     * */
    private void  unLockStock(Long skuId,Long wareId,Integer num,Long taskDetailId){
        wareSkuDao.unlockStock(skuId,wareId,num);
        //将工作单状态改变为已经解锁
        WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity();
        entity.setId(taskDetailId);
        entity.setLockStatus(2);
        wareOrderTaskDetailService.updateById(entity);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            wrapper.eq("sku_id",key);
        }
        String wareId = (String) params.get("wareId");
        if (StringUtils.isNotEmpty(wareId)) {
            wrapper.eq("ware_id",wareId);
        }

        IPage<WareSkuEntity> page = this.page(new Query<WareSkuEntity>().getPage(params),wrapper);

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //判断如果还没有这个库存记录新增
        List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (wareSkuEntities==null||wareSkuEntities.isEmpty()) {
            WareSkuEntity skuEntity = new WareSkuEntity();
            skuEntity.setSkuId(skuId);
            skuEntity.setWareId(wareId);
            skuEntity.setStock(skuNum);
            //如果失败整个事务无须回滚
            try {
                R info = productFeignServcie.info(skuId);
                Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");
                if (info.getCode()==0) {
                    skuEntity.setSkuName(((String) data.get("skuName")));
                }
            }catch (Exception e){
                
            }
            wareSkuDao.insert(skuEntity);
        }else {
            wareSkuDao.addStock(skuId,wareId,skuNum);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            Long count = baseMapper.getSkuStock(skuId);
            System.out.println(skuId+"===" + count);
            skuHasStockVo.setSkuId(skuId);
            skuHasStockVo.setHasStock(count==null?false:count > 0);
            return skuHasStockVo;
        }).collect(Collectors.toList());

        return collect;
    }

    /** description: 锁定库存
     * version: 1.0
     * date: 2021/11/1 17:01
     * */
    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {

        //保存库存工作单的详情
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(taskEntity);

        //1.按照下单的收获地址,找到一个就近仓库,锁定库存
        //1.找到每一个商品在那个仓库有都有库存
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setNum(item.getCount());
            stock.setSkuId(skuId);
            //查询这个商品在哪里有库存
            List<Long> wareIds =wareSkuDao.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareIds);
            return stock;
        }).collect(Collectors.toList());

        Boolean allLock = true;
        //锁定库存
        for (SkuWareHasStock hasStock : collect) {
            Boolean skuStock =false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            if (wareIds ==null || wareIds.size() ==0) {
                throw new NoStockException(skuId);
            }
            for (Long wareId : wareIds) {
                Long count =wareSkuDao.lockSkuStock(skuId,wareId,hasStock.getNum());
                if (count ==1) {
                    skuStock=true;
                    //告诉mq库存锁定成功
                    WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity(null, skuId, "", hasStock.getNum(), taskEntity.getId(), wareId, 1);
                    wareOrderTaskDetailService.save(detailEntity);
                    StockLockedTo lockedTo = new StockLockedTo();
                    lockedTo.setId(taskEntity.getId());
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(detailEntity,stockDetailTo);
                    lockedTo.setDetail(stockDetailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",lockedTo);
                    break;
                }
            }
            if (skuStock ==false) {
                throw new NoStockException(skuId);
            }
        }
        return true;
    }

    @Override
    public void unlockStock(StockLockedTo to) {
            StockDetailTo detail = to.getDetail();
            Long detailId = detail.getId();
            WareOrderTaskDetailEntity byId = wareOrderTaskDetailService.getById(detailId);
            if (byId!=null) {
                Long id = to.getId();
                WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(id);
                String orderSn = taskEntity.getOrderSn();
                R r = orderFeignService.getOrderStatus(orderSn);
                if (r.getCode()==0) {
                    OrderVo data = r.getData(new TypeReference<OrderVo>() {
                    });
                    if (data == null || data.getStatus() == 4) {
                        //订单已经被取消或者不存在,解锁库存
                        if (byId.getLockStatus() == 1) {
                            unLockStock(detail.getSkuId(),detail.getWareId(),detail.getSkuNum(),detailId);
                        }
                    }
                }else {
                    //消息拒收以后重新放到队列里面,让别人继续消费解锁
                    throw new RuntimeException("远程服务调用失败");
                }

            }else {
                //无须解锁
            }
    }

    /** description: 订单关闭,解锁库存
     * version: 1.0 
     * date: 2021/11/4 16:13
     * */
    @Transactional
    @Override
    public void unlockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        //查一下最新状态
        R r = orderFeignService.getOrderStatus(orderSn);
        if (r.getCode()==0) {
            OrderTo orderTo1 = r.getData(new TypeReference<OrderTo>() {
            });
            if (orderTo1.getStatus() == 4) {
                //订单已经被取消,解锁库存
                WareOrderTaskEntity entity =wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
                Long id = entity.getId();
                List<WareOrderTaskDetailEntity> entities = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", id));
                for (WareOrderTaskDetailEntity taskDetailEntity : entities) {
                    if (taskDetailEntity.getLockStatus() == 1) {
                        unLockStock(taskDetailEntity.getSkuId(),taskDetailEntity.getWareId(),taskDetailEntity.getSkuNum(),taskDetailEntity.getId());
                    }
                }

            }
        }else {
            //消息拒收以后重新放到队列里面,让别人继续消费解锁
            throw new RuntimeException("远程服务调用失败");
        }

    }

}